package com.npave.zryhadapter.controller.api;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.util.WxMaConfigHolder;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.npave.zryhadapter.entity.to.UpdateUserMobile2To;
import com.npave.zryhadapter.utils.JacksonUtil;
import com.npave.zryhadapter.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/api/user")
@Validated
@Slf4j
public class UserController {

    @Autowired
    private WxMaService wxMaService;

    @Value("${serverInfo.url}")
    public String serverUrl;
    /**
     * 获取用户绑定手机号信息
     * 从基础库 2.21.2 开始，对获取手机号的接口进行了安全升级，以下是新版本接口
     *
     * @param to
     * @return
     */
    @PostMapping("/mobile2")
    public Object mobile2(@RequestBody UpdateUserMobile2To to,
                          HttpServletRequest request,
                          HttpServletResponse response){
        if (!wxMaService.switchover(to.getAppid())) {
            throw new IllegalArgumentException(String.format("未找到对应appid=[%s]的配置，请核实！", to.getAppid()));
        }

        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getNewPhoneNoInfo(to.getCode());

            log.info("session : {}", phoneNoInfo);

            String token = request.getHeader("X-Token");
            HttpResponse httpResponse = HttpRequest.post(serverUrl + "/api/user/mobile2")
                    .body(JacksonUtil.toJsonStr(phoneNoInfo))
                    .header("X-Token", token)
                    .header("Content-Type","application/json")
                    .timeout(5000)
                    .execute();
            log.info(httpResponse.body());
            if (httpResponse.isOk()) {
                response.setHeader("X-Token", httpResponse.header("X-Token"));
                return httpResponse.body();
            }

            throw new RuntimeException();
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        } finally {
            WxMaConfigHolder.remove();//清理ThreadLocal
        }
    }
    @GetMapping("/subscribe/message/tmplIds")
    public Object subscribeMessageTmpIds(){
        List<String> tmpIds = new ArrayList<>();
        tmpIds.add("cB-hC9hDvDY12OBrISTVfzVj1RaU_bKcbN9tIvC6oEI");
        return ResponseUtil.ok(tmpIds);
    }

//    @PostConstruct
    public void send(){
        WxMaSubscribeMessage message = new WxMaSubscribeMessage();
        message.setToUser("oX2Kc63EkX6MqPPaf9gCiX-OMRzQ");
        message.setTemplateId("cB-hC9hDvDY12OBrISTVf27LPP7AWmDQekIz0f69was");
        message.setPage(null);
        List<WxMaSubscribeMessage.MsgData> data = new ArrayList<>();
        WxMaSubscribeMessage.MsgData characterString9 = new WxMaSubscribeMessage.MsgData("character_string9","XJ1234567890000");
        data.add(characterString9);
        WxMaSubscribeMessage.MsgData phrase4 = new WxMaSubscribeMessage.MsgData("phrase4","测试");
        data.add(phrase4);
        WxMaSubscribeMessage.MsgData thing2 = new WxMaSubscribeMessage.MsgData("thing2","测试");
        data.add(thing2);
        message.setData(data);

        try {
            wxMaService.switchoverTo("wxa05a50bd61323753").getMsgService().sendSubscribeMsg(message);
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
    }
}
